package com.huangkailong.sqlprinter.agent;

import com.huangkailong.sqlprinter.agent.mysql.MysqlSqlPrinterAgent;
import com.huangkailong.sqlprinter.agent.mysql.driver.DriverAgent;
import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtField;
import javassist.CtMethod;

import java.lang.instrument.ClassDefinition;
import java.lang.instrument.Instrumentation;
import java.util.List;
import java.util.Objects;

/**
 * @author huangkailong
 * @since 1.0.0
 */
public class SqlPrinterAgent {
    public static void premain(String agentArg, Instrumentation instrumentation) {
        instrumentation.addTransformer(new MysqlSqlPrinterAgent());
    }

    public static void agentmain(String agentArg, Instrumentation instrumentation) {
        try {
            Class[] loadedClasses = instrumentation.getAllLoadedClasses();
            List<DriverAgent> driverAgents = MysqlSqlPrinterAgent.getDriverAgents();
            for (Class loadedClass : loadedClasses) {
                String name = loadedClass.getName();
                for (DriverAgent driverAgent : driverAgents) {
                    if(driverAgent.isSupport(name)){
                        CtClass ctClass = driverAgent.enhanceClass();
                        instrumentation.redefineClasses(new ClassDefinition(loadedClass, ctClass.toBytecode()));
                        System.out.println(name+"增强成功!");
                        return;
                    }
                }
            }
            System.out.println("未未进行任何增强!");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
